<!--
 * @Description: 找回密码
 * @Author 卞鹏飞 <228443632@qq.com>
 * @create 02/11/24 PM1:08
 -->
<!--setup-->
<script setup>
import { onMounted, getCurrentInstance, reactive, ref, provide } from 'vue'
import SvgIcon from '@/components/svg-icon/index.vue'
import { rules, pattern } from '@shared/base/base-form/rules'
import { ElMessage } from 'element-plus'
import { useVerifyCode } from '@shared/hooks/use-verify-code'
import { to } from 'sf-utils2'
import loginApi from '@/api/modules/user-center/login'
import useRouterPlus from '@/router/use-router-plus'
import { encrypt } from '@/utils/jsencrypt'

const { proxy } = getCurrentInstance()
const props = defineProps({})
const emit = defineEmits([])

/* 状态 */
const { router } = useRouterPlus()
const { start, time } = useVerifyCode()
const formProps = reactive({
  /**
   * 表单实例
   * @type {FormInstance}
   */
  instanceRef: null,
  /**
   * 表单数据
   */
  model: {},

  /**
   * 表单验证规则
   */
  rules: {
    mobile: [{ required: true, message: '请输入手机号', trigger: 'change' }, ...rules.phone],
    code: [{ required: true, message: '请输入验证码', trigger: 'change' }],
    newPassword: [
      { required: true, message: '请输入密码', trigger: 'change' },
      ...rules.passwordV2,
      {
        validator: (rule, value, callback) => {
          if (formProps.model.newPassword2 !== '') {
            if (!formProps.instanceRef) return
            formProps.instanceRef.validateField('newPassword2')
          }
          callback()
        }
      }
    ],
    newPassword2: [
      { required: true, message: '请输入再次确认密码', trigger: 'change' },
      ...rules.passwordV2,
      {
        validator: (rule, value, callback) => {
          if (value !== formProps.model.newPassword) {
            return callback(new Error('两次密码不匹配'))
          }
          return callback()
        }
      }
    ]
  },

  loading: false,

  /** 发送验证码loading */
  sendMsgLoading: false
})

const step = ref(0) // 阶段

/* 方法 */

/**
 * 提交
 * @return {Promise<void>}
 */
async function onSubmit() {
  const [valid, errorFields] = await to(formProps.instanceRef.validate())
  if (!valid) {
    // 校验不通过，提示文字
    const first = Object.values(errorFields).flat().shift()
    return ElMessage.error({
      message: first?.message,
      duration: 5000
    })
  }
  if (step.value == 0) {
    // 第一阶段 获取验证码
    formProps.loading = true

    const reqData = {
      mobile: formProps.model?.mobile,
      code: formProps.model?.code
    }
    const [res, err] = await to(loginApi.captchaSmsCheck(reqData))
    formProps.loading = false
    if (err || res?.code !== 200) return ElMessage.error(res?.message || String(err))
    step.value++
  } else if (step.value == 1) {
    // 第二阶段 设置密码
    const newPassword = formProps.model?.newPassword
    const reqData = {
      newPassword: encrypt(newPassword),
      mobile: formProps.model?.mobile,
      verifyCode: formProps.model?.code
    }
    formProps.loading = true
    const [res, err] = await to(loginApi.changePasswordByMobile(reqData))
    formProps.loading = false
    if (err || res?.code !== 200) return ElMessage.error(res?.message || String(err))
    ElMessage.success('重置密码成功')
    onBackLoginPage()
  }
}

/**
 * 发送验证码
 * @return {Promise<*>}
 */
async function onSendMsg() {
  if (time.value > 0) return
  const mobile = formProps.model?.mobile
  if (!mobile) return ElMessage.error('请输入手机号')
  if (!pattern.phone.test(mobile)) return ElMessage.error('手机号格式错误')
  formProps.sendMsgLoading = true
  const [res, err] = await to(loginApi.captchaSms({ mobile }))
  formProps.sendMsgLoading = false
  if (err || res?.code !== 200) return ElMessage.error(res?.message || String(err))
  ElMessage.success('验证发送成功，请注意查收')
  start()
}

/**
 * 返回登录
 */
function onBackLoginPage() {
  router.replace({
    path: '/login'
  })
}

/* 计算 */

/* 监听 */

/* 周期 */
onMounted(() => {})

/* 暴露 */
defineExpose({
  $: proxy.$
})

provide('__step__', step) // 阶段
</script>

<!--render-->
<template>
  {{ formProps.model }}
  <!--表单-->
  <el-form
    :ref="(el) => (formProps.instanceRef = el)"
    class="mt-20px flex w-[336px] flex-col"
    :model="formProps.model"
    :rules="formProps.rules"
    @keydown.enter="onSubmit"
  >
    <!--标题-->
    <header
      class="mb-20px flex w-full justify-center gap-4 text-center text-[28px] font-medium leading-9"
      aria-label="title"
    >
      <h1>找回密码</h1>
      <span class="self-center rounded bg-orange-50 px-[10px] py-1 text-base text-orange"> 资管端 </span>
    </header>

    <!-- 第一阶段   -->
    <template v-if="step == 0">
      <!--手机号-->
      <el-form-item
        prop="mobile"
        required
      >
        <el-input
          v-model.trim="formProps.model.mobile"
          type="text"
          class="h-12 w-full"
          placeholder="手机号"
          aria-label="手机号"
          name="username"
          autocomplete="username"
          clearable
        >
          <template #prefix>
            <SvgIcon
              svg="login/account"
              size="16"
            />
          </template>
        </el-input>
      </el-form-item>

      <!--验证码-->
      <el-form-item prop="code">
        <el-input
          v-model.trim="formProps.model.code"
          type="text"
          class="w-50 h-12"
          placeholder="验证码"
          aria-label="验证码"
          autocomplete="one-time-code"
        >
          <template #prefix>
            <SvgIcon
              svg="login/verify"
              size="16"
            />
          </template>
        </el-input>

        <div
          :class="[
            `flex-center w-30 ml-4 h-full cursor-pointer rounded bg-primary-50 text-center text-base font-bold leading-10 text-primary`,
            time >= 0 && `pointer-events-none cursor-not-allowed bg-[#F4F5F9] text-[#BFBFBF]`
          ]"
          @click="onSendMsg"
        >
          {{ time > 0 ? `${time}s` : '获取验证码' }}
        </div>
      </el-form-item>

      <div class="pb-24px">
        <el-link
          type="primary"
          :underline="false"
          @click="onBackLoginPage"
        >
          返回登录
        </el-link>
      </div>

      <el-button
        class="h-12 w-full text-base"
        type="primary"
        :loading="formProps.loading"
        @click="onSubmit"
      >
        下一步
      </el-button>
    </template>

    <!-- 第二阶段   -->
    <template v-else-if="step == 1">
      <!--密码1-->
      <el-form-item
        prop="newPassword"
        required
      >
        <el-input
          v-model.trim="formProps.model.newPassword"
          type="password"
          class="h-12 w-full"
          placeholder="密码"
          aria-label="手机号"
          autocomplete="current-password"
          clearable
          show-password
        >
          <template #prefix>
            <SvgIcon
              svg="login/password"
              size="16"
            />
          </template>
        </el-input>
      </el-form-item>

      <!--密码2-->
      <el-form-item
        prop="newPassword2"
        required
      >
        <el-input
          v-model.trim="formProps.model.newPassword2"
          type="password"
          class="h-12 w-full"
          placeholder="密码"
          aria-label="手机号"
          autocomplete="current-password"
          clearable
          show-password
        >
          <template #prefix>
            <SvgIcon
              svg="login/password"
              size="16"
            />
          </template>
        </el-input>
      </el-form-item>

      <el-button
        class="h-12 w-full text-base"
        type="primary"
        :loading="formProps.loading"
        @click="onSubmit"
      >
        重置
      </el-button>
    </template>
  </el-form>
</template>

<!--style-->
<style scoped lang="less">
.page {
}
</style>
